<template>
  <el-dialog
    v-model="visible"
    :title="t('trash.dialogs.deleteTitle')"
    width="500px"
    :before-close="handleClose"
  >
    <div class="delete-dialog">
      <!-- 警告信息 -->
      <div class="warning-section">
        <el-alert
          :title="t('trash.dialogs.deleteWarning')"
          type="error"
          :closable="false"
          show-icon
        >
          <template #default>
            <div class="warning-content">
              <p>{{ t('trash.dialogs.deleteDescription') }}</p>
              <ul>
                <li>{{ t('trash.dialogs.deletePoint1') }}</li>
                <li>{{ t('trash.dialogs.deletePoint2') }}</li>
                <li>{{ t('trash.dialogs.deletePoint3') }}</li>
              </ul>
              <p class="warning-text">{{ t('trash.dialogs.deleteConfirmText') }}</p>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 文件列表 -->
      <div class="files-section">
        <h4>{{ t('trash.dialogs.deleteFilesCount', { count: files.length }) }}</h4>
        <div class="files-list">
          <div
            v-for="file in files"
            :key="file.id"
            class="file-item"
          >
            <el-icon class="file-icon">
              <component :is="getFileIcon(file)" />
            </el-icon>
            <div class="file-info">
              <div class="file-name">{{ file.originalName }}</div>
              <div class="file-meta">
                <span class="file-size">
                  {{ file.isDirectory ? t('trash.fileList.folder') : formatFileSize(file.fileSize || 0) }}
                </span>
                <span class="deleted-time">
                  {{ t('trash.fileList.deletedAt') }} {{ formatDeletedTime(file.deletedAt || '') }}
                </span>
                <span 
                  v-if="isExpiringSoon(file.deletedAt || '')"
                  class="expiry-info"
                >
                  {{ calculateExpiryTime(file.deletedAt || '') }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <div class="stat-item">
          <span class="stat-label">{{ t('trash.dialogs.fileCount') }}</span>
          <span class="stat-value">{{ files.length }} {{ t('trash.stats.totalFiles') }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">{{ t('trash.dialogs.totalSize') }}</span>
          <span class="stat-value">{{ formatFileSize(totalSize) }}</span>
        </div>
        <div v-if="expiringSoonCount > 0" class="stat-item">
          <span class="stat-label">{{ t('trash.dialogs.expiringSoonLabel') }}</span>
          <span class="stat-value warning">{{ t('trash.dialogs.expiringSoonFiles', { count: expiringSoonCount }) }}</span>
        </div>
      </div>

      <!-- 确认输入 -->
      <div class="confirm-section">
        <p class="confirm-text">
          {{ t('trash.dialogs.confirmDeleteText') }} <strong>"{{ t('trash.dialogs.confirmDeleteKeyword') }}"</strong> {{ t('trash.dialogs.confirmDeletePrompt') }}
        </p>
        <el-input
          v-model="confirmText"
          :placeholder="t('trash.dialogs.confirmDeletePlaceholder')"
          :class="{ 'confirm-input': true, 'valid': isConfirmValid }"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ t('trash.dialogs.cancel') }}</el-button>
        <el-button
          type="danger"
          @click="handleConfirm"
          :loading="loading"
          :disabled="!isConfirmValid"
        >
          {{ t('trash.dialogs.deleteConfirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { Folder, Document, Picture, VideoPlay, Mic } from '@element-plus/icons-vue'
import type { FileInfo } from '@/types/file'
import {
  formatFileSize,
  calculateExpiryTime,
  isExpiringSoon,
  getFileTypeIcon
} from '@/api/modules/trash'

// ==================== 国际化 ====================

const { t } = useI18n()

// ==================== Props & Emits ====================

interface Props {
  modelValue: boolean
  files: FileInfo[]
  loading?: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm'): void
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

const emit = defineEmits<Emits>()

// ==================== 状态管理 ====================

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const confirmText = ref('')

// ==================== 计算属性 ====================

const isConfirmValid = computed(() => {
  return confirmText.value.trim() === t('trash.dialogs.confirmDeleteKeyword')
})

const totalSize = computed(() => {
  return props.files
    .filter(file => !file.isDirectory)
    .reduce((total, file) => total + (file.fileSize || 0), 0)
})

const expiringSoonCount = computed(() => {
  return props.files.filter(file => isExpiringSoon(file.deletedAt || '')).length
})

// ==================== 方法定义 ====================

/**
 * 格式化删除时间（国际化版本）
 */
const formatDeletedTime = (deletedAt: string): string => {
  const date = new Date(deletedAt)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMinutes = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

  if (diffMinutes < 1) {
    return t('trash.time.justNow')
  } else if (diffMinutes < 60) {
    return t('trash.time.minutesAgo', { minutes: diffMinutes })
  } else if (diffHours < 24) {
    return t('trash.time.hoursAgo', { hours: diffHours })
  } else {
    return t('trash.time.daysAgo', { days: diffDays })
  }
}

/**
 * 获取文件图标组件
 */
const getFileIcon = (file: FileInfo) => {
  if (file.isDirectory) return Folder
  
  const iconType = getFileTypeIcon(file.originalName, file.isDirectory)
  const iconMap = {
    image: Picture,
    video: VideoPlay,
    audio: Mic,
    folder: Folder,
    file: Document
  }
  
  return iconMap[iconType as keyof typeof iconMap] || Document
}

/**
 * 处理确认
 */
const handleConfirm = () => {
  if (isConfirmValid.value) {
    emit('confirm')
  }
}

/**
 * 处理关闭
 */
const handleClose = () => {
  if (!props.loading) {
    visible.value = false
    confirmText.value = ''
  }
}
</script>

<style scoped>
.delete-dialog {
  padding: 8px 0;
}

.warning-section {
  margin-bottom: 20px;
}

.warning-content p {
  margin: 8px 0;
  line-height: 1.5;
}

.warning-content ul {
  margin: 8px 0;
  padding-left: 20px;
}

.warning-content li {
  margin: 4px 0;
  line-height: 1.4;
}

.warning-text {
  font-weight: 600;
  color: var(--el-color-danger);
}

.files-section {
  margin-bottom: 20px;
}

.files-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.files-list {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  background-color: var(--el-fill-color-lighter);
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.file-item:last-child {
  border-bottom: none;
}

.file-icon {
  margin-right: 8px;
  color: var(--el-text-color-regular);
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 13px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  font-size: 12px;
  color: var(--el-text-color-regular);
  display: flex;
  gap: 8px;
}

.deleted-time {
  color: var(--el-text-color-placeholder);
}

.expiry-info {
  color: var(--el-color-warning);
  font-weight: 500;
}

.stats-section {
  margin-bottom: 20px;
  padding: 12px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.stat-item:last-child {
  margin-bottom: 0;
}

.stat-label {
  font-size: 13px;
  color: var(--el-text-color-regular);
}

.stat-value {
  font-size: 13px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.stat-value.warning {
  color: var(--el-color-warning);
}

.confirm-section {
  margin-bottom: 8px;
}

.confirm-text {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.confirm-input {
  width: 100%;
}

.confirm-input.valid :deep(.el-input__inner) {
  border-color: var(--el-color-success);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
